from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import reverse
from django.shortcuts import HttpResponse
from django import views
from django.db import DatabaseError
from web import models
from web.forms.student import StudentForm
from web.forms.student import StudentForm2

class StudentView(views.View):
    '''
    学生列表
    '''
    def get(self,request):

        # models.Role.objects.values('permissions__parent__name')
        data_list=models.Student.objects.all()
        return render(request,'student_list.html',{'data_list':data_list})


class StudentAddView(views.View):
    '''
    添加学生
    '''
    def get(self,request):
        student_form=StudentForm()
        return render(request,'student_add.html',{'form':student_form})
    def post(self,request):

        student_form=StudentForm2(data=request.POST)
        if student_form.is_valid():
            student_form.save()
            # print(reverse('student:student_list'))
            return redirect('/student/list/')
        else:
            return render(request,'student_add.html',{'form':student_form})


class StudentEditView(views.View):
    '''
    学生编辑
    '''
    def get(self,request,pk):
        student_obj=models.Student.objects.get(pk=pk)
        student_form=StudentForm2(instance=student_obj)
        return render(request,'student_add.html',{'form':student_form})
    def post(self,request,pk):
        student_obj=models.Student.objects.get(pk=pk)
        student_form=StudentForm2(instance=student_obj,data=request.POST)
        if student_form.is_valid():
            student_form.save()
            return redirect(reverse('student:student_list'))
        else:
            return render(request,'student_list.html',{'form':student_form})

class StudentDeleteView(views.View):

    def get(self,request,pk):
        student_obj=models.Student.objects.get(pk=pk)
        student_form=StudentForm()
        return render(request,'student_delete.html',{'form':student_form})
    def post(self,request,pk):
        try:
            models.Student.objects.filter(pk=pk).delete()
        except DatabaseError:
            print('数据库错误')
            return HttpResponse('删除失败')
        return redirect(reverse('student:student_list'))